package com.zhong.filter;

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author zbg on 2019-02-14 14:45:13
 * 所有的请求必须经过网关进行过滤
 */
@Slf4j
public class MappingFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //这里模拟DB
        log.info("进入zuul过滤器");
        Map<String, String> map = Maps.newHashMap();
        map.put("/movice", "/microservice-consumer");
        map.put("/user", "/microservice-provider");

        String uri = httpServletRequest.getRequestURI();
        String val = map.get(uri);
        log.info("val:{}", val);
        if (StringUtils.isNotEmpty(val)) {
            WrappedHttpRequest fakeRequest = WrappedHttpRequest.wrap(httpServletRequest);
            fakeRequest.setRequestURI(val + uri);
            filterChain.doFilter(fakeRequest, httpServletResponse);
        } else {
            filterChain.doFilter(httpServletRequest, httpServletResponse);
        }
    }

}
